package com.tianci.appstore.database;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.skyworth.webSDK.webservice.tcappstore.AppMainPageData;
import com.skyworth.webSDK.webservice.tcappstore.AppMainPagebeans;
import com.skyworth.webSDK.webservice.tcappstore.AppMainSubSorts;
import com.tianci.appstore.dataprovider.AppDataProvider;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyAppDetailData;
import com.tianci.appstore.ui.data.SkyCategoryData;
import com.tianci.appstore.ui.data.SkyMainAppData;
import com.tianci.appstore.ui.data.SkySndCgyData;
import com.tianci.appstore.utils.DownLoadPicture;
import com.tianci.appstore.utils.FileTools;
import com.tianci.appstore.utils.SkyConstants;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AppStoreDB {
    private static final String tag = "lqw";
    private List<AppMainPageData> mainPageList = new ArrayList<AppMainPageData>();
    private static AppStoreDB storeDB = null;
    private SkyDBUtil dbUtil = null;

    private String BASE_PATH = "";
    private String DB_FILE = "";
    private String ICON_PATH = "";
    private String BIG_SCREEN_PATH = "";

    private static final String TABLE_NAME = "appstore";
    private static final String PKG_NAME = "pkgtopath";
    private static final String APPCONFIG_NAME = "appconfig";
    private static final String[][] APPSTOREMAIN_TABLE_COLUMNSANDTYPES = {
            {"id", "INTEGER PRIMARY KEY"}, {"sortid", "TEXT"}, {"sortname", "TEXT"},
            {"subsortid", "TEXT "}, {"subsortname", "TEXT"}, {"subsortbackground", "TEXT"},
            {"appid", "TEXT "}, {"iconurl", "TEXT"}, {"appname", "TEXT"},
            {"pkg", "TEXT"}, {"adpicurl", "TEXT"}, {"type", "TEXT"}};

    private static final String[][] APPSTOREAPPPATH_TABLE_COLUMNSANDTYPES = {
            {"pkg", "TEXT PRIMARY KEY"}, {"path", "TEXT"}, {"extra", "TEXT "}};

    private static final String[][] APPSTOREAPPPATH_TABLE_APPCONFIG = {
            {"id", "INTEGER PRIMARY KEY"}, {"pkg", "TEXT"}, {"myapp", "INTEGER"},
            {"extra", "TEXT "}};

    public static synchronized AppStoreDB getInstance() {
        if (null == storeDB) {
            storeDB = new AppStoreDB(CoocaaApplication.getContext());
        }
        return storeDB;
    }

    private Context mContext = null;

    public AppStoreDB(Context c) {
        mContext = c;
        initPath();
        if (!(new File(BASE_PATH).exists()))
            new File(BASE_PATH).mkdir();
        dbUtil = new SkyDBUtil(DB_FILE);
        if (!(new File(DB_FILE).exists())) {
            deleteOldDB();
            dbUtil.createTable(TABLE_NAME, APPSTOREMAIN_TABLE_COLUMNSANDTYPES);
            dbUtil.createTable(PKG_NAME, APPSTOREAPPPATH_TABLE_COLUMNSANDTYPES);
            dbUtil.createTable(APPCONFIG_NAME, APPSTOREAPPPATH_TABLE_APPCONFIG);
        }

        File dirFile = new File(ICON_PATH);
        if (!dirFile.exists())
            dirFile.mkdir();
        File dirFile2 = new File(BIG_SCREEN_PATH);
        if (!dirFile2.exists())
            dirFile2.mkdir();
    }

    public String getIconPath() {
        if (ICON_PATH.equals("")) {
            initPath();
        }
        return ICON_PATH;
    }

    public String getBigScreenPath() {
        if (BIG_SCREEN_PATH.equals("")) {
            initPath();
        }
        return BIG_SCREEN_PATH;
    }

    public void initPath() {
        BASE_PATH = mContext.getFilesDir() + "/appstore/";
        DB_FILE = BASE_PATH + "appstore" + getAppVersionCode(mContext) + ".db";
        ICON_PATH = mContext.getCacheDir() + "/icon_res/";
        BIG_SCREEN_PATH = mContext.getCacheDir() + "/big_screen/";
    }

    public synchronized static String getAppVersionCode(Context context) {
        String version = "";
        String pkgname = context.getPackageName();
        try {
            version = String
                    .valueOf(context.getPackageManager().getPackageInfo(pkgname, 0).versionCode);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        LogUtils.d("db", "getAPPVersionCode:" + version);
        return version;
    }

    public void deleteOldDB() {
        LogUtils.d("db", "deleteOldDB:" + BASE_PATH);
        FileTools.delAllFile(BASE_PATH);
    }

    public synchronized boolean addMainPageData(List<AppMainPageData> mainList) {
        if (mainList == null || mainList.size() < 1) {
            return false;
        }
        LogUtils.d("db", "addMainPageData---mainList.size()=" + mainList.size());
        dbUtil.deleteDb(TABLE_NAME, " id > ?", new String[]{"0"});
        for (int i = 0; i < mainList.size(); i++) {
            LogUtils.d("db", "---" + mainList.get(i).sortName);
            String sortId = mainList.get(i).sortId;
            String sortName = mainList.get(i).sortName;
            List<AppMainSubSorts> subSort = mainList.get(i).subSorts;
            List<AppMainPagebeans> pageBeans = mainList.get(i).apps;
            for (int j = 0; j < subSort.size(); j++) {
                LogUtils.d("db", "---&&&" + subSort.get(j).sortName);
                String subSortId = subSort.get(j).sortId;
                String subSortName = subSort.get(j).sortName;
                // String subSortBackground = subSort.get(j).flag.toString();
                String subSortBackground = subSort.get(j).imgurl;
                Object[] values = {null, sortId, sortName, subSortId, subSortName,
                        subSortBackground, null, null, null, null, null, null};
                dbUtil.insert_replace(TABLE_NAME, values);
            }
            for (int k = 0; k < pageBeans.size(); k++) {
                String appId = pageBeans.get(k).appid;
                String appIcon = pageBeans.get(k).icon;
                String appName = pageBeans.get(k).name;
                String pkg = pageBeans.get(k).packageName;
                String adpic = pageBeans.get(k).adpic;
                String type = pageBeans.get(k).apptype;
                LogUtils.d("db", "---***" + appName + " pkg:" + pkg);
                if (k < 3) {
                    DownLoadPicture.downLoadPicture(adpic, ICON_PATH + appId);
                }
                DownLoadPicture.downLoadPicture(appIcon, ICON_PATH + appId + "icon");
                Object[] values = {null, sortId, sortName, null, null, null, appId, appIcon,
                        appName, pkg, adpic, type};
                dbUtil.insert_replace(TABLE_NAME, values);
            }
        }
        return true;
    }

    public synchronized List<SkyAppBaseData> getMainPageDataFromDB(final SkyCategoryData c) {
        String sql = "SELECT * FROM " + TABLE_NAME;
        final List<SkyAppBaseData> appDataList = new ArrayList<SkyAppBaseData>();
        dbUtil.query(sql, null, new SkyDBUtil.QueryHandler() {
            @Override
            public Object onResult(Cursor cursor, Object obj) {
                // TODO Auto-generated method stub
                boolean hasData = cursor.moveToFirst();
                // LogUtils.d(tag, "getMainPageData--cursor.getCount():"+cursor.getCount());
                List<SkyAppBaseData> tempList = new ArrayList<SkyAppBaseData>();
                while (hasData) {
                    String sortId = cursor.getString(cursor.getColumnIndex("sortid"));
                    if (sortId != null && sortId.equals(c.id)) {
                        String subSortId = cursor.getString(cursor.getColumnIndex("subsortid"));
                        String subSortName = cursor.getString(cursor.getColumnIndex("subsortname"));
                        String subSortBackground = cursor.getString(cursor
                                .getColumnIndex("subsortbackground"));
                        if (subSortId != null && !subSortId.equals("")) {
                            SkyAppBaseData appData = new SkySndCgyData(subSortId, subSortName,
                                    subSortBackground, null);
                            LogUtils.d("db", "SkySndCgyData---size:" + appDataList.size());
                            if (appDataList.size() < SkyConstants.SUBSORTCOUNT) {
                                appDataList.add(appData);
                            }
                        }
                        String appid = cursor.getString(cursor.getColumnIndex("appid"));
                        String iconurl = cursor.getString(cursor.getColumnIndex("iconurl"));
                        String appname = cursor.getString(cursor.getColumnIndex("appname"));
                        String pkg = cursor.getString(cursor.getColumnIndex("pkg"));
                        String adpicurl = cursor.getString(cursor.getColumnIndex("adpicurl"));
                        String type = cursor.getString(cursor.getColumnIndex("type"));
                        if (appid != null && !appid.equals("")) {
                            // LogUtils.d(tag, "getMainPageData--appname:"+appname);
                            if (appDataList.size() < SkyConstants.SUBSORTCOUNT) {
                                for (int m = 0; m < SkyConstants.SUBSORTCOUNT - appDataList.size(); m++) {
                                    SkyAppBaseData appData = new SkySndCgyData("1000" + m,
                                            "备用" + m, "", "");
                                    ((SkySndCgyData) appData).setCount(0);
                                    appDataList.add(appData);
                                }
                            }
                            LogUtils.d("db", "SkyMainAppData---size:" + appDataList.size());
                            SkyAppBaseData appData2 = new SkyMainAppData(appid, appname, iconurl,
                                    adpicurl, "", type);
                            appData2.setPackageName(pkg);
                            SkyAppDetailData.AppStatus status = SkyAppDetailData.AppStatus.NOT_DOWNLOADED;
                            status = AppDataProvider.getInstance().isAppInstalled(pkg);
                            if(status == SkyAppDetailData.AppStatus.INSTALLED)
                                tempList.add(appData2);
                            else
                                appDataList.add(appData2);
                        }
                    }
                    hasData = cursor.moveToNext();
                }

                int size = appDataList.size();
                LogUtils.d(tag,"getMainPageDataFromDB appDataList  size:"+size);
                if(size < 12)
                {
                    int n = (12 - size) >= tempList.size() ? tempList.size():(12 - size);
                    LogUtils.d(tag,"getMainPageDataFromDB n:"+n);
                    for(int m = 0; m < n; m ++)
                    {
                        appDataList.add(tempList.get(m));
                    }
                }


                return appDataList;
            }

        });
        return appDataList;
    }

    public synchronized List<SkyCategoryData> getCategoryData() {
        String sql = "SELECT DISTINCT sortid,sortname FROM " + TABLE_NAME;
        final List<SkyCategoryData> list = new ArrayList<SkyCategoryData>();
        dbUtil.query(sql, null, new SkyDBUtil.QueryHandler() {

            @Override
            public Object onResult(Cursor cursor, Object obj) {
                // TODO Auto-generated method stub
                boolean hasData = cursor.moveToFirst();
                // LogUtils.d(tag, "getCategoryData----cursor.getCount():"+cursor.getCount());
                while (hasData) {
                    // LogUtils.d(tag, "getCategoryData----sortId:");
                    String sortId = cursor.getString(cursor.getColumnIndex("sortid"));
                    String sortName = cursor.getString(cursor.getColumnIndex("sortname"));
                    SkyCategoryData c = new SkyCategoryData(sortId, sortName);
                    // LogUtils.d(tag, "getCategoryData----sortId:" + sortId);
                    list.add(c);
                    hasData = cursor.moveToNext();
                }
                return list;
            }

        });
        return list;
    }

    public synchronized boolean addAppLogoPath(String pkg, String path, String extra) {
        Object[] values = {pkg, path, extra};
        LogUtils.d("aaa", "addAppLogoPath----pkg:" + pkg + "  " + path);
        dbUtil.insert_replace(PKG_NAME, values);
        return true;
    }

    public synchronized List<String> getPathByPkg(String pkg) {
        String sql = "SELECT * FROM " + PKG_NAME + " WHERE pkg = '" + pkg + "'";
        final List<String> pathList = new ArrayList<String>();
        dbUtil.query(sql, null, new SkyDBUtil.QueryHandler() {

            @Override
            public Object onResult(Cursor cursor, Object obj) {
                // TODO Auto-generated method stub
                boolean hasData = cursor.moveToFirst();
                while (hasData) {
                    // LogUtils.d(tag, "getCategoryData----sortId:");
                    String path = cursor.getString(cursor.getColumnIndex("path"));
                    pathList.add(path);
                    hasData = cursor.moveToNext();
                }
                return pathList;
            }

        });
        return pathList;
    }

    public synchronized boolean addAppConfigData(String pkg, int myapp) {
        Object[] values = {null, pkg, myapp, ""};
        // LogUtils.d("test", "addAppLogoPath----pkg:"+pkg+"  "+ myapp);
        dbUtil.insert_replace(APPCONFIG_NAME, values);
        return true;
    }

    public synchronized HashMap<String, Boolean> getAppConfigData() {
        String sql = "SELECT * FROM " + APPCONFIG_NAME;
        final HashMap<String, Boolean> mAppMap = new HashMap<String, Boolean>();
        dbUtil.query(sql, null, new SkyDBUtil.QueryHandler() {

            @Override
            public Object onResult(Cursor cursor, Object obj) {
                // TODO Auto-generated method stub
                boolean hasData = cursor.moveToFirst();
                while (hasData) {
                    String pkg = cursor.getString(cursor.getColumnIndex("pkg"));
                    int appconfig = cursor.getInt(cursor.getColumnIndex("myapp")); // 0 false 1 true
                    if (appconfig == 0) {
                        mAppMap.put(pkg, false);
                    } else {
                        mAppMap.put(pkg, true);
                    }
                    // LogUtils.d("test", "getAppConfigData----pkg:"+pkg);
                    hasData = cursor.moveToNext();
                }
                mAppMap.put("com.tianci.appstore", false);
                return mAppMap;
            }

        });
        return mAppMap;
    }
}
